import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseInterceptors,
  UploadedFiles,
  UploadedFile,
  Inject,
  OnModuleInit,
  OnApplicationBootstrap,
  OnModuleDestroy,
  BeforeApplicationShutdown,
  OnApplicationShutdown,
  ValidationPipe,
  HttpException,
  HttpStatus,
  BadRequestException,
  VERSION_NEUTRAL,
  UsePipes,
  ParseFilePipe,
  MaxFileSizeValidator,
  FileTypeValidator,
} from '@nestjs/common';
import { PersonService } from './person.service';
import { CreatePersonDto } from './dto/create-person.dto';
import { UpdatePersonDto } from './dto/update-person.dto';
import {
  AnyFilesInterceptor,
  FileInterceptor,
  FilesInterceptor,
  FileFieldsInterceptor,
} from '@nestjs/platform-express';
import { AppService } from 'src/app.service';
import { storage } from './setUploadDir';
import { FileSizeValidationPipePipe } from 'src/file-size-validation-pipe.pipe';
import { MyFileValidator } from './MyFileValidator';

@Controller({
  path: 'api/person',
  version: VERSION_NEUTRAL,
})
export class PersonController
  implements
    OnModuleInit,
    OnApplicationBootstrap,
    OnModuleDestroy,
    BeforeApplicationShutdown,
    OnApplicationShutdown
{
  constructor(private readonly personService: PersonService) {}

  @Inject('person2')
  private readonly person2: {
    name: string;
    age: string;
  };

  // @Inject(AppService)
  // private readonly appService: AppService;

  @Inject('CONFIG_OPTIONS')
  private readonly configOptions: Record<string, any>;

  onModuleInit() {
    console.log('PersonController onModuleInit~');
  }

  onApplicationBootstrap() {
    console.log('PersonController onApplicationBootstrap~');
  }
  onModuleDestroy() {
    console.log('PersonService onModuleDestroy~');
  }

  beforeApplicationShutdown(signal: string) {
    console.log('PersonService beforeApplicationShutdown~', signal);
  }
  onApplicationShutdown() {
    console.log('PersonService onApplicationShutdown~');
  }
  @Get('find')
  query(@Query('name') name: string, @Query('age') age: number) {
    console.log('handle...');

    return `received: name=${name},age=${age}`; // ${this.appService.getHello()}
  }

  // @Get(':id')
  // urlParam(@Param('id') id: string) {
  //   return `received id: ${id}`;
  //   // return this.personService.findOne(+id);
  // }

  @Post()
  body(@Body(new ValidationPipe()) createPersonDto: CreatePersonDto) {
    console.log('body的值是===', createPersonDto);
    return `返回值==${JSON.stringify(createPersonDto)}`;
  }

  @Get('/err')
  a(@Query('id') id: string) {
    // 自定义错误信息
    throw new BadRequestException('Forbidden123');
    throw new HttpException('Forbidden123', HttpStatus.BAD_REQUEST);
    // return `received id: ${id}`;
    // return this.personService.findOne(+id);
  }

  @Post('singleFile')
  @UseInterceptors(
    FileInterceptor('singleFile', {
      dest: 'uploads',
    }),
  )
  singleFile(
    @UploadedFile(FileSizeValidationPipePipe) file: Array<Express.Multer.File>,
    @Body() createPersonDto: CreatePersonDto,
  ) {
    console.log('file==', file);
    console.log('createPersonDto==', createPersonDto);
    return `received: ${JSON.stringify(createPersonDto)}`;
  }

  @Post('multiFile')
  @UseInterceptors(
    FilesInterceptor('multiFile', 2, {
      // dest: 'uploads',
      storage,
    }),
  )
  multiFile(
    @UploadedFiles(
      new ParseFilePipe({
        validators: [
          new MaxFileSizeValidator({ maxSize: 10 * 1024 }),
          new FileTypeValidator({ fileType: 'image/jpeg' }),
          new MyFileValidator({}), // 自定义验证器
        ],
        // 自定义错误信息
        exceptionFactory: (errors) => {
          throw new HttpException(
            '自定义错误==' + errors,
            HttpStatus.BAD_REQUEST,
          );
        },
      }),
    )
    files: Array<Express.Multer.File>,
    @Body() createPersonDto: CreatePersonDto,
  ) {
    console.log('files==', files);
    console.log('createPersonDto==', createPersonDto);
    return `received: ${JSON.stringify(createPersonDto)}`;
  }

  @Post('namesFiles')
  @UseInterceptors(
    // 多个文件名
    FileFieldsInterceptor(
      [
        {
          name: 'm1',
          maxCount: 2,
        },
        {
          name: 'm2',
          maxCount: 2,
        },
      ],
      {
        dest: 'uploads',
      },
    ),
  )
  namesFiles(
    @UploadedFiles(
      new ParseFilePipe({
        exceptionFactory: (errors) =>
          new HttpException(errors, HttpStatus.UNPROCESSABLE_ENTITY),
      }),
    )
    files: Array<Express.Multer.File>,
    @Body() createPersonDto: CreatePersonDto,
  ) {
    console.log('files==', files);
    console.log('createPersonDto==', createPersonDto);
    return `received: ${JSON.stringify(createPersonDto)}`;
  }
}
